import AnchorTitle from '../../components/anchor-title'
import ProductItem from '../products/components/product-item'
import Paginator from '../../components/paginator'
import { fetcher } from '@/src/utils/fetcher'
import { getTranslations } from 'next-intl/server'
import { cookies } from 'next/headers'
import SearchBar from './components/search-bar'
import { objectToQueryString } from '@/src/utils/object-to-query-string'
import EmptyBoundary from '../../components/empty-boundary'

interface PageProps {
  searchParams: {
    keyword?: string
    page?: string
  }
}

const EmptyPage: React.FC = async () => {
  const t = await getTranslations()
  return (
    <div className='flex justify-center items-center w-full h-[18.75rem] 2xl:h-[28.125rem] text-[#999999] text-[0.875rem] 2xl:text-[1.125rem]'>
      {t('emptyPage')}
    </div>
  )
}

const Page: React.FC<PageProps> = async (props) => {
  const { searchParams } = props
  const t = await getTranslations('searchResult')
  const cookieStore = cookies()

  const currentPage = searchParams.page ? Number(searchParams.page) : 1
  const getProductsQuery = () => {
    let productsQuery = {
      page: currentPage.toString(),
    } as any
    if (searchParams.keyword) {
      productsQuery['fontkey'] = searchParams.keyword
    }
    return productsQuery
  }
  const products = (await fetcher<WithPaginator<Product>>(
    `/api/index/cpList?${objectToQueryString(getProductsQuery())}`,
    { cookieStore }
  )) || {
    list: [],
    p: 0,
    total: 0,
  }

  return (
    <>
      <AnchorTitle title={t('title')}>
        <div className='hidden lg:block'>
          <SearchBar defaultValue={searchParams.keyword || ''} />
        </div>
      </AnchorTitle>
      <div className='h-[0.84375rem] lg:h-[1.8125rem] 2xl:h-[2.71875rem]' />
      <div className='lg:hidden'>
        <SearchBar defaultValue={searchParams.keyword || ''} />
        <div className='h-[0.6875rem]' />
      </div>
      {/* 列表 */}
      <EmptyBoundary
        isEmpty={products.list.length === 0}
        fallback={<EmptyPage />}
      >
        <div className='grid grid-cols-1 lg:grid-cols-3 gap-4 2xl:gap-6'>
          {products.list.map((product) => {
            return (
              <ProductItem
                key={product.id}
                id={product.id.toString()}
                picture={product.image}
                desc={product.con}
                year={product.year}
                manufacturer={product.manufacturer_name}
                model={product.model_name}
                hours={product.hours}
                category={product.category_name}
                price={product.price}
              />
            )
          })}
        </div>
      </EmptyBoundary>
      <div className='h-[1.875rem]' />
      <Paginator
        initialPage={currentPage}
        total={Math.ceil(products.total / products.p) || 1}
      />
      <div className='h-[2.34475rem]' />
    </>
  )
}

export default Page
